<template>
  <div class="workflow-scheduler-container">
    <!-- 页面头部 -->
    <div class="page-header-content">
      <div class="flex-between mb-24">
        <div>
          <h3 style="margin: 0; color: #303133">工作流调度</h3>
          <p style="margin: 8px 0 0; color: #909399">可视化设计和管理数据处理工作流，类似 DolphinScheduler</p>
        </div>
        <div class="header-actions">
          <el-button @click="handleImport">
            <el-icon><Upload /></el-icon>
            导入工作流
          </el-button>
          <el-button type="primary" @click="handleCreate">
            <el-icon><Plus /></el-icon>
            创建工作流
          </el-button>
        </div>
      </div>

      <!-- 统计卡片 -->
      <el-row :gutter="16">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-value">{{ statistics.totalWorkflows }}</div>
              <div class="stat-label">总工作流数</div>
            </div>
            <el-icon class="stat-icon" color="#409eff"><DataAnalysis /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-value">{{ statistics.runningWorkflows }}</div>
              <div class="stat-label">运行中</div>
            </div>
            <el-icon class="stat-icon" color="#67c23a"><Timer /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-value">{{ statistics.todayExecutions }}</div>
              <div class="stat-label">今日执行</div>
            </div>
            <el-icon class="stat-icon" color="#e6a23c"><TrendCharts /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-value">{{ statistics.successRate }}%</div>
              <div class="stat-label">成功率</div>
            </div>
            <el-icon class="stat-icon" color="#f56c6c"><SuccessFilled /></el-icon>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 工作流列表 -->
    <el-card class="workflow-list-card">
      <template #header>
        <div class="flex-between">
          <span>工作流列表</span>
          
          <!-- 搜索和筛选 -->
          <div class="search-controls">
            <el-input
              v-model="searchForm.name"
              placeholder="搜索工作流名称"
              style="width: 200px; margin-right: 12px"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            
            <el-select v-model="searchForm.status" placeholder="状态" style="width: 120px; margin-right: 12px" clearable>
              <el-option label="全部" value="" />
              <el-option label="运行中" value="running" />
              <el-option label="已停止" value="stopped" />
              <el-option label="已暂停" value="paused" />
            </el-select>
            
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </div>
        </div>
      </template>

      <!-- 工作流网格视图 -->
      <div class="workflow-grid">
        <div
          v-for="workflow in workflowList"
          :key="workflow.id"
          class="workflow-card"
          @click="handleViewWorkflow(workflow)"
        >
          <!-- 工作流卡片头部 -->
          <div class="workflow-card-header">
            <div class="workflow-info">
              <div class="workflow-name">{{ workflow.name }}</div>
              <div class="workflow-desc">{{ workflow.description }}</div>
            </div>
            <el-dropdown @command="(cmd) => handleWorkflowAction(cmd, workflow)" @click.stop>
              <el-button circle size="small">
                <el-icon><MoreFilled /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="edit">
                    <el-icon><Edit /></el-icon>
                    编辑
                  </el-dropdown-item>
                  <el-dropdown-item command="copy">
                    <el-icon><CopyDocument /></el-icon>
                    复制
                  </el-dropdown-item>
                  <el-dropdown-item command="export">
                    <el-icon><Download /></el-icon>
                    导出
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" divided>
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>

          <!-- 工作流预览图 -->
          <div class="workflow-preview">
            <WorkflowMiniGraph :nodes="workflow.nodes" :edges="workflow.edges" />
          </div>

          <!-- 工作流状态和统计 -->
          <div class="workflow-stats">
            <div class="status-row">
              <el-tag :type="getStatusTagType(workflow.status)" size="small">
                <el-icon style="margin-right: 4px">
                  <component :is="getStatusIcon(workflow.status)" />
                </el-icon>
                {{ getStatusLabel(workflow.status) }}
              </el-tag>
              
              <div class="stats-info">
                <span class="stat-item">
                  <el-icon><Document /></el-icon>
                  {{ workflow.nodeCount }} 节点
                </span>
                <span class="stat-item">
                  <el-icon><Clock /></el-icon>
                  {{ formatTime(workflow.lastRunTime) }}
                </span>
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="workflow-actions">
            <el-button
              size="small"
              type="primary"
              @click.stop="handleRunWorkflow(workflow)"
              :disabled="workflow.status === 'running'"
            >
              <el-icon><VideoPlay /></el-icon>
              {{ workflow.status === 'running' ? '运行中' : '立即执行' }}
            </el-button>
            
            <el-button
              size="small"
              @click.stop="handleViewLogs(workflow)"
            >
              <el-icon><Document /></el-icon>
              查看日志
            </el-button>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="workflowList.length === 0" class="empty-state">
          <el-empty description="暂无工作流">
            <el-button type="primary" @click="handleCreate">创建第一个工作流</el-button>
          </el-empty>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[12, 24, 48]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 执行历史对话框 -->
    <ExecutionHistoryDialog
      v-model="historyDialogVisible"
      :workflow-id="currentWorkflowId"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import WorkflowMiniGraph from './components/WorkflowMiniGraph.vue'
import ExecutionHistoryDialog from './components/ExecutionHistoryDialog.vue'
import { formatTime } from '@/utils/date'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const workflowList = ref([])
const historyDialogVisible = ref(false)
const currentWorkflowId = ref(null)

// 统计数据
const statistics = reactive({
  totalWorkflows: 12,
  runningWorkflows: 3,
  todayExecutions: 28,
  successRate: 94.2
})

// 搜索表单
const searchForm = reactive({
  name: '',
  status: ''
})

// 分页
const pagination = reactive({
  page: 1,
  size: 12,
  total: 0
})

// 生命周期
onMounted(() => {
  fetchWorkflowList()
})

// 方法
const fetchWorkflowList = async () => {
  loading.value = true
  try {
    // 模拟 API 调用
    await new Promise(resolve => setTimeout(resolve, 800))
    
    // 模拟工作流数据
    workflowList.value = [
      {
        id: 1,
        name: '用户数据处理工作流',
        description: '处理用户注册、登录、行为数据的完整工作流',
        status: 'running',
        nodeCount: 8,
        lastRunTime: new Date(Date.now() - 3600000),
        nodes: [
          { id: 'source', type: 'data-source', label: '数据源' },
          { id: 'transform', type: 'data-transform', label: '数据转换' },
          { id: 'target', type: 'data-target', label: 'Doris' }
        ],
        edges: [
          { source: 'source', target: 'transform' },
          { source: 'transform', target: 'target' }
        ]
      },
      {
        id: 2,
        name: '销售报表生成',
        description: '每日销售数据汇总和报表生成',
        status: 'stopped',
        nodeCount: 5,
        lastRunTime: new Date(Date.now() - 86400000),
        nodes: [
          { id: 'mysql', type: 'data-source', label: 'MySQL' },
          { id: 'etl', type: 'data-transform', label: 'ETL' },
          { id: 'doris', type: 'data-target', label: 'Doris' },
          { id: 'report', type: 'data-output', label: '报表' }
        ],
        edges: [
          { source: 'mysql', target: 'etl' },
          { source: 'etl', target: 'doris' },
          { source: 'doris', target: 'report' }
        ]
      },
      {
        id: 3,
        name: '实时数据流处理',
        description: 'Kafka 实时数据流到 Doris 的处理管道',
        status: 'running',
        nodeCount: 6,
        lastRunTime: new Date(Date.now() - 1800000),
        nodes: [
          { id: 'kafka', type: 'data-source', label: 'Kafka' },
          { id: 'stream', type: 'data-transform', label: '流处理' },
          { id: 'doris', type: 'data-target', label: 'Doris' }
        ],
        edges: [
          { source: 'kafka', target: 'stream' },
          { source: 'stream', target: 'doris' }
        ]
      },
      {
        id: 4,
        name: '数据质量检查',
        description: '定期检查数据质量并生成质量报告',
        status: 'paused',
        nodeCount: 4,
        lastRunTime: new Date(Date.now() - 7200000),
        nodes: [
          { id: 'doris', type: 'data-source', label: 'Doris' },
          { id: 'check', type: 'data-transform', label: '质量检查' },
          { id: 'alert', type: 'data-output', label: '告警' }
        ],
        edges: [
          { source: 'doris', target: 'check' },
          { source: 'check', target: 'alert' }
        ]
      }
    ]
    
    pagination.total = workflowList.value.length
  } catch (error) {
    ElMessage.error('获取工作流列表失败')
  } finally {
    loading.value = false
  }
}

const handleCreate = () => {
  router.push('/workflow-scheduler/create')
}

const handleImport = () => {
  ElMessage.info('导入功能开发中...')
}

const handleViewWorkflow = (workflow) => {
  router.push(`/workflow-scheduler/edit/${workflow.id}`)
}

const handleRunWorkflow = (workflow) => {
  ElMessageBox.confirm(
    `确认立即执行工作流 "${workflow.name}"？`,
    '确认执行',
    {
      confirmButtonText: '执行',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    workflow.status = 'running'
    ElMessage.success('工作流执行成功')
  }).catch(() => {})
}

const handleViewLogs = (workflow) => {
  currentWorkflowId.value = workflow.id
  historyDialogVisible.value = true
}

const handleWorkflowAction = (command, workflow) => {
  switch (command) {
    case 'edit':
      router.push(`/workflow-scheduler/edit/${workflow.id}`)
      break
    case 'copy':
      ElMessage.success('工作流复制成功')
      break
    case 'export':
      ElMessage.success('工作流导出成功')
      break
    case 'delete':
      ElMessageBox.confirm(
        `确认删除工作流 "${workflow.name}"？`,
        '确认删除',
        {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        ElMessage.success('删除成功')
        fetchWorkflowList()
      }).catch(() => {})
      break
  }
}

const handleSearch = () => {
  pagination.page = 1
  fetchWorkflowList()
}

const handleSizeChange = () => {
  fetchWorkflowList()
}

const handleCurrentChange = () => {
  fetchWorkflowList()
}

// 工具方法
const getStatusLabel = (status) => {
  const labels = {
    'running': '运行中',
    'stopped': '已停止',
    'paused': '已暂停'
  }
  return labels[status] || status
}

const getStatusTagType = (status) => {
  const types = {
    'running': 'success',
    'stopped': 'info',
    'paused': 'warning'
  }
  return types[status] || 'info'
}

const getStatusIcon = (status) => {
  const icons = {
    'running': 'VideoPlay',
    'stopped': 'VideoPause',
    'paused': 'VideoPlay'
  }
  return icons[status] || 'QuestionFilled'
}
</script>

<style scoped>
.workflow-scheduler-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.page-header-content {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-card :deep(.el-card__body) {
  padding: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 8px;
}

.stat-icon {
  font-size: 32px;
  opacity: 0.8;
}

.workflow-list-card {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.workflow-list-card :deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.search-controls {
  display: flex;
  align-items: center;
}

.workflow-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 16px;
  flex: 1;
}

.workflow-card {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 16px;
  background: #fff;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  flex-direction: column;
  height: 280px;
}

.workflow-card:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.workflow-card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.workflow-info {
  flex: 1;
  margin-right: 12px;
}

.workflow-name {
  font-weight: 600;
  font-size: 16px;
  color: #303133;
  margin-bottom: 4px;
  line-height: 1.4;
}

.workflow-desc {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.workflow-preview {
  flex: 1;
  margin-bottom: 16px;
  min-height: 100px;
}

.workflow-stats {
  margin-bottom: 16px;
}

.status-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stats-info {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #909399;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.workflow-actions {
  display: flex;
  gap: 8px;
}

.workflow-actions .el-button {
  flex: 1;
}

.empty-state {
  grid-column: 1 / -1;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.pagination-container {
  margin-top: 16px;
  text-align: right;
}

@media (max-width: 768px) {
  .workflow-grid {
    grid-template-columns: 1fr;
  }
  
  .search-controls {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .search-controls > * {
    width: 100% !important;
  }
}
</style> 